import { useState } from 'react';
import { Table, Button, Modal, Select } from 'antd';
import type { TableColumnType } from 'antd';

import { mockList } from '@/utils/data';
import type { User } from '@/utils/data';
import styles from './index.less';

const peoples = mockList();
const opts = [
  {
    value: 'default',
    text: 'Default',
  },
  {
    value: 'age-up',
    text: 'Form Age Up',
  },
  {
    value: 'age-down',
    text: 'Form Age Down',
  },
];

export default function App() {
  var [lists, setLists] = useState(peoples);
  function handleRemove(item: User) {
    Modal.confirm({
      title: 'Remove',
      content: 'Are you sure?',
      onOk: () => {
        let rs: User[] = [];
        lists.map((l) => {
          if (l.username != item.username) {
            rs.push(l);
          }
        });
        setLists(rs);
      },
    });
  }
  function upSort(arr: User[]): User[] {
    if (Array.isArray(arr)) {
      for (var i = arr.length - 1; i > 0; i--) {
        for (var j = 0; j < i; j++) {
          if ((arr[j].age as number) < (arr[j + 1].age || 0)) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
          }
        }
      }
      return arr;
    }
    return [];
  }
  function downSort(arr: User[]): User[] {
    if (Array.isArray(arr)) {
      for (var i = arr.length - 1; i > 0; i--) {
        for (var j = 0; j < i; j++) {
          if ((arr[j].age as number) > (arr[j + 1].age || 0)) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
          }
        }
      }
      return arr;
    }
    return [];
  }
  function handleSortList(v: string) {
    if (v == 'default') {
      setLists(peoples);
    }

    if (v == 'age-up') {
      var s: User[] = upSort([...peoples]);
      setLists(s);
    }
    if (v == 'age-down') {
      var s: User[] = downSort([...peoples]);
      setLists(s);
    }
  }
  const columns: TableColumnType<User>[] = [
    {
      title: 'Name',
      dataIndex: 'username',
    },
    {
      title: 'Age',
      dataIndex: 'age',
    },
    {
      title: 'Operation',
      align: 'center',
      render(record: User) {
        return <Button onClick={() => handleRemove(record)}>Remove</Button>;
      },
    },
  ];
  return (
    <div>
      <div className={styles.header}>
        <span>Sort：</span>
        <Select
          defaultValue="default"
          onChange={handleSortList}
          style={{ width: 150 }}
        >
          {opts.map((opt) => (
            <Select.Option value={opt.value}>{opt.text}</Select.Option>
          ))}
        </Select>
      </div>
      {/*
      dataSource array
      columns    array
      bordered.  boolean
      rowKey.    [string | function] for list unique key
       */}
      <Table dataSource={lists} columns={columns} bordered rowKey="name" />
    </div>
  );
}
